<template>
  <div class="supplier-and-contract">
    <div class="block">
      <header>
        <h2 class="required">
          供应商选择
        </h2>
      </header>
      <section>
        <el-form>
          <el-form-item label="供应商">
            <el-select
              v-model="supplier_id"
              placeholder="请选择"
              @change="onChangeSupplier"
            >
              <el-option
                v-for="item in rows_supplies"
                :key="item.supplierCode"
                :label="item.supplierName"
                :value="item.supplierCode"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </section>
    </div>
    <div class="block select-contract-part">
      <header>
        <h2 class="required">
          授权合同选择
        </h2>
      </header>
      <section class="select-contract-table">
        <el-radio-group
          v-model="contract_id"
          class="w100p"
          @change="onChangeContract"
        >
          <el-editable
            v-loading="contractTableLoading"
            :need-pagination="true"
            :columns="COLUMNS_CONTRACT"
            :payload="payload_contracts"
            height="200"
            @reload="onLoadData"
          >
            <template #default-checkbox="{ row }">
              <el-radio :label="row.contractUnitId">
                {{ '' }}
              </el-radio>
            </template>
          </el-editable>
        </el-radio-group>
      </section>
    </div>
    <el-dialog
      title="更换供应商"
      :visible.sync="dialogVisible.supplier"
      width="30%"
      :before-close="handleCloseSupplierDialog"
    >
      <span
        >更换供应商后，对应的已选择的退货类型或退{{
          isExchange ? '换' : ''
        }}货产品都会清空</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="supplierDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="supplierDialogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="更换合同"
      :visible.sync="dialogVisible.contract"
      width="30%"
      :before-close="handleCloseContractDialog"
    >
      <span
        >更换授权合同后，对应的已选择的退货类型或退{{
          isExchange ? '换' : ''
        }}货产品都会清空</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="contractDialogRefuse">取 消</el-button>
        <el-button type="primary" @click="contractDialogConfirm"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ElEditable from '@components/el-editable';
import {
  selectsupplierList,
  selectListBysupplier,
  getOrderType
} from '@api/m_mall_web_v1';
import * as CONSTS from './index.const';

export default {
  components: {
    ElEditable
  },
  props: {
    isExchange: {
      type: Boolean,
      default: false
    },
    supplierId: String,
    contractId: String,
    returnTypeName: String,
    products: {
      type: Array,
      default: () => []
    },
    isFirstMount: Boolean
  },
  data() {
    return {
      ...CONSTS,
      table_query: {},
      rows_supplies: [], // 产品线列表数据
      payload_contracts: {}, // 产品线数据
      supplier_id: '',
      contract_id: '',
      return_type_name: '',
      full_data: {
        supplierName: '',
        supplierCode: '',
        contractName: '',
        contractCode: '',
        originalFactoryName: '',
        originalFactoryCode: '',
        productLineName: '',
        productLineCode: ''
      },
      storaged: {
        supplier_id: '',
        contract_id: ''
      },
      dialogVisible: {
        supplier: false,
        contract: false
      },
      contractTableLoading: false,
      curPageSize: 20
    };
  },
  computed: {
    // 判断是否存在产品信息或订单类型，如果存在则为true，用于在切换供应商或合同时提示
    isNeedAlert() {
      if (this.products.length > 0) {
        return true;
      }
      return false;
    }
  },
  watch: {
    // returnTypeName: {
    //   handler(val) {
    //     this.return_type_name = val;
    //   },
    //   immediate: true
    // },
    supplierId: {
      handler(val) {
        if (val !== '') {
          this.supplier_id = val;
          this.onLoadData({ number: 1, size: this.curPageSize });
          // 当重新获取合同列表时，手动清空合同绑定的及缓存的值
          // 如果是第一次加载，则不把合同置为空
          // 只要没切换supplierId，或者ContractId就视为第一次加载
          if (!this.isFirstMount) {
            this.contract_id = '';
            this.storaged.contract_id = '';
            this.full_data.contract = '';
            // this.returnTypeName = '';
            // 清空相应数据后还要更新
            this.$emit('update:contractId', this.contract_id);
          }
        }
      },
      immediate: true
    },
    contractId: {
      handler(val) {
        this.contract_id = val;
        if (this.isFirstMount) this.storaged.contract_id = this.contract_id;
      },
      immediate: true
    }
  },
  created() {
    this.getSuppliers();
  },
  methods: {
    getOrderType(contract) {
      this.$axios({
        method: 'post',
        url: getOrderType,
        data: {
          busModel: contract.busModel,
          supplierCode: '000'
        }
      }).then(res => {
        const result = res.data.payload || {};
        this.$emit('getOrderTypeRows', result);
      });
    },
    getSuppliers() {
      this.$axios({
        method: 'post',
        url: selectsupplierList,
        data: { busModelList: [1, 2] }
      }).then(res => {
        this.rows_supplies = res.data.payload || [];
      });
    },
    // 由于合同特殊性，要特别前端判断唯一性，创建contractUnitId
    getContractUnitId(item) {
      return `${item.productLineCode || ''}${item.originalFactoryCode ||
        ''}${item.channelType || ''}${item.busModel ||
        ''}${item.contractInvalidDate || ''}`;
    },
    async onLoadData(pager) {
      // 这里，手动给this.curPageSize赋值，是因为：
      // 该参数是由el-editable组件内返回，但，当supplier_id在change的时候，会触发watch手动调用。
      // 所以，要在里面获取到pageSize的值以同步。
      this.curPageSize = pager.size;
      if (!this.supplier_id) {
        this.$message.error('请选择供应商');
        return;
      }
      this.contractTableLoading = true;
      this.$axios({
        method: 'post',
        url: selectListBysupplier,
        data: {
          page: pager.number,
          pageSize: pager.size,
          supplierCode: this.supplier_id,
          busModelList: [1, 2]
        }
      })
        .then(res => {
          this.payload_contracts = res.data.payload;
          this.payload_contracts.content.forEach(item => {
            this.$set(item, 'contractUnitId', this.getContractUnitId(item));
          });
          const contract = this.payload_contracts.content.find(
            item => item.contractUnitId === this.contract_id
          );
          if (contract !== undefined) {
            const supplier = this.rows_supplies.find(
              item => item.supplierCode === this.supplier_id
            );
            this.full_data.supplierName = supplier.supplierName;
            this.full_data.supplierCode = supplier.supplierCode;

            Object.assign(this.full_data, contract);
            this.$emit('change', this.full_data);
          }
        })
        .finally(() => {
          this.contractTableLoading = false;
        });
    },
    supplierCommonProgress(supplierId) {
      // 走剩下的逻辑
      this.$emit('update:supplierId', supplierId);
      const suppliy = this.rows_supplies.find(
        item => item.supplierCode === supplierId
      );
      // 为了上一层的取值，这里额外再赋值一下
      this.full_data.suppliy = suppliy;
      Object.assign(this.full_data, suppliy);
      // this.returnTypeName = '';
      // this.$emit('update:returnTypeName', '');
      // 这里通过emit给上级传递数据，触发watch，加载数据
      this.$emit('update:isFirstMount', false);
      this.$emit('change', this.full_data);
    },
    onChangeSupplier(value) {
      // if (this.isNeedAlert || this.returnTypeName) {
      if (this.isNeedAlert) {
        this.dialogVisible.supplier = true;
      } else {
        this.storaged.supplier_id = value;
        this.supplierCommonProgress(value);
      }
    },
    supplierDialogConfirm() {
      this.dialogVisible.supplier = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.supplier_id = this.supplier_id;
      // 加这个字段，是因为无论取消还是确定都要更新
      this.supplierCommonProgress(this.supplier_id);
    },
    supplierDialogRefuse() {
      this.dialogVisible.supplier = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      this.supplier_id = this.storaged.supplier_id;
    },
    handleCloseSupplierDialog() {
      this.supplierDialogRefuse();
    },
    contractCommonProgress(contractId) {
      this.$emit('update:contractId', contractId);
      this.storaged.contract_id = contractId;
      const contract = this.payload_contracts.content.find(
        item => item.contractUnitId === contractId
      );
      // this.returnTypeName = '';
      // this.$emit('update:returnTypeName', '');
      // 为了上一层的取值，这里额外再赋值一下
      this.full_data.contract = contract;
      this.$emit('update:isFirstMount', false);
      this.$emit('change', this.full_data);
      this.getOrderType(contract);
    },
    onChangeContract(contractId) {
      if (this.isNeedAlert) {
        // if (this.isNeedAlert || this.returnTypeName) {
        this.dialogVisible.contract = true;
      } else {
        this.storaged.contract_id = contractId;
        this.contractCommonProgress(contractId);
      }
    },
    contractDialogConfirm() {
      this.dialogVisible.contract = false;
      // 确定更新，要更新暂存数据，重新赋值
      this.storaged.contract_id = this.contract_id;
      this.contractCommonProgress(this.contract_id);
    },
    contractDialogRefuse() {
      this.dialogVisible.contract = false;
      // 取消的话，要把当前暂存的数据重新赋值给当前状态值
      this.contract_id = this.storaged.contract_id;
    },
    handleCloseContractDialog() {
      this.contractDialogRefuse();
    }
  }
};
</script>

<style lang="less">
.w100p {
  width: 100%;
}
</style>
